package oa.web.controller;

import javax.servlet.RequestDispatcher;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import oa.core.Constant;
import oa.core.MyCookie;
import oa.web.service.LoginService;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;

import java.io.IOException;

@Controller

public class Login {

	@Autowired
	private LoginService loginService;

	@RequestMapping("login")
	public String index(HttpServletRequest req, HttpServletResponse rep, ModelMap map){
        Cookie cookie = MyCookie.getCookie(Constant.LOGIN_COOKIE_NAME, req);
        int loginStatus = Constant.LOGIN_STATUS_INIT;
        String CurrentUser = null;
        if(cookie!=null && loginService.CookieLogin(cookie.getValue())){
            String token = cookie.getValue();
            token = Constant.decodeBASE64(token);
            String user_pass[] = token.split("_");
            CurrentUser = user_pass[0];
        }else {
            String username = req.getParameter("username");
            String password = req.getParameter("password");
            loginStatus = loginService.isLogin(username, password,Constant.USERNAME_PASS_LOGIN);
            if(loginStatus != Constant.LOGIN_STATUS_LOGIN_SUCCESS){
                return "redirect:login.jsp";
            }else{
                String token = username+"_"+Constant.getMD5Instance().toMd5(password);
                token = Constant.encodeBASE64(token);
                Cookie loginCookie = MyCookie.addCookie(Constant.LOGIN_COOKIE_NAME,token,null,null,-1);
                CurrentUser = username;
                rep.addCookie(loginCookie);
            }
        }
        Cookie nextCookie = MyCookie.getCookie(Constant.NEXTURL_COOKIE_NAME,req);
        if(nextCookie!=null && nextCookie.getMaxAge()!= Constant.COOKIE_NULL_AGE){
            String nextUrl = nextCookie.getValue();
            if(nextUrl!=null && !nextUrl.equals("")){
                try {
                    //the deletedCookie must be set before sendRedirect, or the response will be not the current response
                    Cookie deletedCookie = MyCookie.addCookie(nextCookie.getName(),null,null,null,Constant.COOKIE_NULL_AGE);
                    rep.addCookie(deletedCookie);
                    rep.sendRedirect(nextUrl);
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        map.addAttribute("CurrentUser",CurrentUser);
        return "index";
	}

}
